package com.example.demo.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录成功后的处理器
 * 转发或者重定向，有代码实现逻辑
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private String url;
    private Boolean isRedirect;

    public MyAuthenticationSuccessHandler(String url,boolean isRedirect){
        this.isRedirect=isRedirect;
        this.url=url;
    }

    /**
     *
     * @param httpServletRequest    请求对象 httpServletRequest.getRequestDispatcher().forward()
     * @param httpServletResponse   响应对象 httpServletResponse.sendRedirect()
     * @param authentication        用户认证（登录）成功后的对象，其中包含用户名和权限集合
     * @author 陈先生
     * @date 2021/4/6 9:39
     * @return void
     * @throws
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {


        System.out.println("这是自定义登录认证逻辑。。。。。。。。。。。。。");
        if(isRedirect){
            httpServletResponse.sendRedirect(url);
        }else {
            httpServletRequest.getRequestDispatcher(url).forward(httpServletRequest, httpServletResponse);
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Boolean getRedirect() {
        return isRedirect;
    }

    public void setRedirect(Boolean redirect) {
        isRedirect = redirect;
    }
}
